use std::collections::HashMap;

use crate::api::user_api;
use crate::model::order::Order;
use crate::model::order_add_dto::OrderAddDto;
// use crate::model::OrderItem;
use crate::model::{Goodimg, OrderVo, OrderitemVo};
use crate::resp::resp::Resp;

use crate::util::logger;
use crate::{service, RB};

use actix_web::{post, get, put, web, Responder, HttpResponse};

use chrono::{DateTime, FixedOffset, Utc};
use serde::{Deserialize, Serialize};
// use rocket::serde::json::Json;
use serde_json::json;

#[allow(dead_code, unused_imports)]
#[post("/order")]
pub async fn add_order(order_add_dto: web::Json<OrderAddDto>) -> impl Responder {
    return service::add_order(order_add_dto).await;
}

#[allow(dead_code, unused_imports)]
#[get("/orders")]
pub async fn select_all_order_vo() -> impl Responder {
    let rb = RB.clone();
    let data: Result<Vec<Order>, rbatis::rbdc::Error> =
        rb.query_decode("select * from `order`", vec![]).await;
    match data {
        Ok(mut orders) => {
            let mut order_vos: Vec<OrderVo> = Vec::new();
            for order in orders.iter_mut() {
                let orderitem_vos: Result<Vec<OrderitemVo>, rbatis::rbdc::Error> = rb
                    .query_decode(
                        &("select * from orderitem where oid='".to_owned()
                            + &order.clone().oid.unwrap()
                            + "'"),
                        vec![],
                    )
                    .await;
                let mut orderitem_vos = orderitem_vos.unwrap();
                for orderitem_vo in orderitem_vos.iter_mut() {
                    let sql: String = format!(
                        "select * from goodimg where gid={:?}",
                        &orderitem_vo.clone().gid.unwrap()
                    );
                    let imglist: Result<Vec<Goodimg>, rbatis::rbdc::Error> =
                        rb.query_decode(&sql, vec![]).await;
                    let mut imglist = imglist.unwrap();
                    let mut url_list: Vec<String> = Vec::new();
                    for img in imglist.iter_mut() {
                        url_list.push(img.clone().url.unwrap())
                    }
                    dbg!(&url_list);
                    orderitem_vo.imglist = Some(url_list);
                }
                let resp = user_api::sel_seller(order.clone().uid.unwrap().as_str()).await;
                let seller = resp.data;
                let order_vo = OrderVo {
                    seller,
                    info: order.clone(),
                    glist: Some(orderitem_vos),
                };
                order_vos.push(order_vo);
            }
            let msg = "获取所有订单成功";
            return HttpResponse::Ok().json(
                json!(Resp {
                symbol: 50,
                r#type: "success",
                code: 200,
                msg: msg,
                data: order_vos
            }));
        }
        Err(_) => {
            return HttpResponse::Ok().json(json!(Resp::bad("未知错误", -500, ())));
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PathF1 {
    pub oid: String
}
#[allow(dead_code, unused_imports)]
#[get("/order/{oid}")]//F1
pub async fn get_order_vo_by_oid(path: web::Path<PathF1>) -> impl Responder {
    let oid = path.oid.clone();
    let rb = RB.clone();
    let sql = format!("select * from `order` where oid={:?}", oid);
    let data: Result<Order, rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
    match data {
        Ok(order) => {
            let orderitem_vos: Result<Vec<OrderitemVo>, rbatis::rbdc::Error> = rb
                .query_decode(
                    &("select * from orderitem where oid='".to_owned()
                        + &order.clone().oid.unwrap()
                        + "'"),
                    vec![],
                )
                .await;
            let mut orderitem_vos = orderitem_vos.unwrap();
            for orderitem_vo in orderitem_vos.iter_mut() {
                let sql: String = format!(
                    "select * from goodimg where gid={:?}",
                    &orderitem_vo.clone().gid.unwrap()
                );
                let imglist: Result<Vec<Goodimg>, rbatis::rbdc::Error> =
                    rb.query_decode(&sql, vec![]).await;
                let mut imglist = imglist.unwrap();
                let mut url_list: Vec<String> = Vec::new();
                for img in imglist.iter_mut() {
                    url_list.push(img.clone().url.unwrap())
                }
                dbg!(&url_list);
                orderitem_vo.imglist = Some(url_list);
            }
            let resp = user_api::sel_seller(order.clone().uid.unwrap().as_str()).await;
            let seller = resp.data;
            let order_vo = OrderVo {
                seller,
                info: order.clone(),
                glist: Some(orderitem_vos),
            };
            return HttpResponse::Ok().json(json!(Resp::ok("查询成功！", 0, order_vo)));
        }
        Err(_) => {
            return HttpResponse::Ok().json(json!(Resp::fail("查询失败，没有相关订单", 0, TmpData1 { oid: &oid })));
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PathF2 {
    phone: String
}
#[allow(dead_code, unused_imports)]
#[get("/order?{phone}")] //F2
pub async fn get_order_vo_by_phone(path: web::Path<PathF2>) -> impl Responder {
    let phone = path.phone.clone();
    let rb = RB.clone();
    let sql = format!("select * from `order` where bphone={:?}", phone);
    let data: Result<Vec<Order>, rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
    match data {
        Ok(mut orders) => {
            if orders.len() == 0 {
                let mut datax: HashMap<&str, &str> = HashMap::new();
                datax.insert("phone", &phone);
                return HttpResponse::Ok().json(json!(Resp::fail("订单不存在", -100, datax)));
            }
            let mut order_vos: Vec<OrderVo> = Vec::new();
            for order in orders.iter_mut() {
                let orderitem_vos: Result<Vec<OrderitemVo>, rbatis::rbdc::Error> = rb
                    .query_decode(
                        &("select * from orderitem where oid='".to_owned()
                            + &order.clone().oid.unwrap()
                            + "'"),
                        vec![],
                    )
                    .await;
                let mut orderitem_vos = orderitem_vos.unwrap();
                for orderitem_vo in orderitem_vos.iter_mut() {
                    let sql: String = format!(
                        "select * from goodimg where gid={:?}",
                        &orderitem_vo.clone().gid.unwrap()
                    );
                    let imglist: Result<Vec<Goodimg>, rbatis::rbdc::Error> =
                        rb.query_decode(&sql, vec![]).await;
                    let mut imglist = imglist.unwrap();
                    let mut url_list: Vec<String> = Vec::new();
                    for img in imglist.iter_mut() {
                        url_list.push(img.clone().url.unwrap())
                    }
                    dbg!(&url_list);
                    orderitem_vo.imglist = Some(url_list);
                }
                let resp = user_api::sel_seller(order.clone().uid.unwrap().as_str()).await;
                let seller = resp.data;
                let order_vo = OrderVo {
                    seller,
                    info: order.clone(),
                    glist: Some(orderitem_vos),
                };
                order_vos.push(order_vo);
            }
            return HttpResponse::Ok().json(json!(Resp::ok("查询成功", 0, order_vos)));
        }
        Err(_) => {
            let mut datax: HashMap<&str, &str> = HashMap::new();
            datax.insert("phone", &phone);
            return HttpResponse::Ok().json(json!(Resp::bad("未知错误", -500, datax)));
        }
    }
}


///商家变更订单状态
#[allow(dead_code, unused_imports, unreachable_code)]
#[put("/updateOrderState")]
// #[put("/order/{oid}?<ostate>")]  //F3
pub async fn upd_order_state_by_oid(web::Query((oid,ostate)): web::Query<(String,i32)>) -> impl Responder {
    let rb = RB.clone();
    let sql: String = format!("select * from `order` where oid={:?}", oid);
    let data: Result<Order, rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
    match data {
        Ok(order) => {
            if let -1 = order.ostate {
                return HttpResponse::Ok().json(json!(Resp::fail("订单已经取消过了，无法再取消", -105, ())));
            } else if let 1 = order.ostate {
                return HttpResponse::Ok().json(json!(Resp::fail("订单已完成，无法取消", -104, ())));
            }
            let mut resp_ok = Resp::ok("商家确认", 102, TmpData1 { oid: &oid });
            match ostate {
                2_i32 => {
                    //从0（刚下单，待确认）-> 2待支付（已确认）
                }
                3_i32 => {
                    resp_ok.symbol = 103;
                    resp_ok.msg = "备货完成";
                }
                4_i32 => {
                    resp_ok.symbol = 104;
                    resp_ok.msg = "开始发货";
                }
                -1_i32 => {
                    resp_ok.symbol = 105;
                    resp_ok.msg = "取消订单";
                }
                _ => {
                    let mut datax: HashMap<&str, &str> = HashMap::new();
                    datax.insert("oid", &oid);
                    let ostate_str = ostate.to_string();
                    datax.insert("ostate", &ostate_str);
                    return HttpResponse::Ok().json(json!(Resp::fail("不被允许的状态", -103, datax)));
                }
            }
            let sql = format!("update `order` set ostate={} where oid={:?}", ostate, oid);
            let _x: Result<(), rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
            let log_str = format!("{}{}", resp_ok.msg, order.oid.clone().unwrap());
            logger::info(log_str);
            return HttpResponse::Ok().json(json!(resp_ok));
        }
        Err(_) => {
            return HttpResponse::Ok().json(json!(Resp::fail("订单不存在", -100, TmpData1 { oid: &oid })));
        }
    }
}

///客户取消订单接口
#[allow(dead_code, unused_imports)]
#[put("/client/order")] //于E版本开始，规范化替代原路由
pub async fn client_cancle_order_by_oid(web::Query(oid): web::Query<String>) -> impl Responder {
    let rb = RB.clone();
    let sql: String = format!("select * from `order` where oid={:?}", oid);
    let data: Result<Order, rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
    match data {
        Ok(order) => {
            if let -1 = order.ostate {
                return HttpResponse::Ok().json(json!(Resp::fail(
                    "订单已经取消过了，无法再取消",
                    -101,
                    TmpData1 { oid: &oid }
                )));
            } else if let 1 = order.ostate {
                return HttpResponse::Ok().json(json!(Resp::fail("订单已完成，无法取消", -100, TmpData1 { oid: &oid })));
            } else if let 4 = order.ostate {
                return HttpResponse::Ok().json(json!(Resp::fail("订单已发货，无法取消", -99, TmpData1 { oid: &oid })));
            }
            let sql = format!("update `order` set ostate={} where oid={:?}", -1, oid);
            let _x: Result<(), rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
            let log_str = format!("取消订单: {}", order.oid.clone().unwrap());
            logger::info(log_str);
            return HttpResponse::Ok().json(json!(Resp::ok("成功取消订单", 100, TmpData1 { oid: &oid })));
        }
        Err(_) => {
            return HttpResponse::Ok().json(json!(Resp::fail("订单不存在", -102, TmpData1 { oid: &oid })));
        }
    }
}

#[allow(dead_code, unused_imports, unused_must_use)]
#[put("/finishOrder")]
// #[put("/finish/order/<oid>")]
pub async fn finish_order_by_oid(web::Query(oid): web::Query<String>) -> impl Responder {
    let rb = RB.clone();
    let sql: String = format!("select * from `order` where oid={:?}", oid);
    let data: Result<Order, rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
    let now: DateTime<Utc> = Utc::now();
    let timezone_east = FixedOffset::east_opt(8 * 60 * 60).unwrap();
    let now = now.with_timezone(&timezone_east);
    let now: String = format!("{}", now.format("%Y-%m-%d %H:%M:%S"));
    // let now1 = format!("{}", now.format("%Y-%m-%d "));
    match data {
        Ok(order) => {
            if order.ostate == -1 {
                let msg = format!("oid为{oid}的订单已取消，无法完成！");
                return HttpResponse::Ok().json(json!(Resp::fail(&msg, 0, TmpData1 { oid: &oid })));
            }
            let etime = now.as_str();
            let sql = format!(
                "update `order` set ostate={},etime={:?} where oid={:?}",
                1, etime, oid
            );
            rb.query(&sql, vec![]).await;
            let log_str = format!("完成订单:{}, 完成时间: {}", order.oid.clone().unwrap(), etime);
            logger::info(log_str);
            return HttpResponse::Ok().json(json!(Resp::ok("订单完成！", 0, TmpData1 { oid: &oid })));
        }
        Err(_) => {
            let msg = format!("oid为{oid}的订单不存在！");
            return HttpResponse::Ok().json(json!(Resp::fail(&msg, -102, TmpData1 { oid: &oid })));
        }
    }
}

//分页获取订单接口
#[allow(dead_code, unused_imports, non_snake_case)]
#[get("/page/order")]
pub async fn select_order_by_page(
    web::Query((pageNum,pageSize,Type,uid,ostate)): web::Query<(i32,i32,String,Option<String>,Option<i32>)>
) -> impl Responder {
    let rb = RB.clone();
    let limit = pageSize;
    let offset = pageSize * (pageNum - 1);
    let mut sql: String = format!("select * from `order`");
    let condition1 = "";
    match ostate {
        Some(s)=> {
            let s_all = vec![-1,0,1,2,3,4,5];
            match s_all.binary_search(&s) {
                Ok(_index) => {
                    let condition1 = format!("where ostate={}", s);
                    sql = format!("{} {}", sql, condition1);
                },
                Err(_err) => {
                    return HttpResponse::Ok().json(json!(Resp::fail("不存在的ostate", 0, ())));
                }
            }
        },
        None => {
            if Type == "1" {
                let condition1 = "where (ostate<>-1 or ostate<>1)";
                sql = format!("{} {}", sql, condition1);
            } else if Type == "2" {
                let condition1 = "where (ostate=-1 or ostate=1)";
                sql = format!("{} {}", sql, condition1);
            }
        }
    }
    match uid {
        Some(uid) => {
            if uid.trim() == "" {
                //...
            } else {
                let condition2 = format!("uid={:?}", uid);
                if condition1 == "" {
                    sql = format!("{} and {}", sql, condition2);
                } else {
                    sql = format!("{} where {}", sql, condition2);
                }
            }
        }
        None => {
            //
        }
    }
    sql = format!("{} limit {} offset {}", sql, limit, offset);
    let data: Result<Vec<Order>, rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
    match data {
        Ok(mut orders) => {
            let mut order_vos: Vec<OrderVo> = Vec::new();
            for order in orders.iter_mut() {
                let orderitem_vos: Result<Vec<OrderitemVo>, rbatis::rbdc::Error> = rb
                    .query_decode(
                        &("select * from orderitem where oid='".to_owned()
                            + &order.clone().oid.unwrap()
                            + "'"),
                        vec![],
                    )
                    .await;
                let mut orderitem_vos = orderitem_vos.unwrap();
                for orderitem_vo in orderitem_vos.iter_mut() {
                    let sql: String = format!(
                        "select * from goodimg where gid={:?}",
                        &orderitem_vo.clone().gid.unwrap()
                    );
                    let imglist: Result<Vec<Goodimg>, rbatis::rbdc::Error> =
                        rb.query_decode(&sql, vec![]).await;
                    let mut imglist = imglist.unwrap();
                    let mut url_list: Vec<String> = Vec::new();
                    for img in imglist.iter_mut() {
                        url_list.push(img.clone().url.unwrap())
                    }
                    // dbg!(&url_list);
                    orderitem_vo.imglist = Some(url_list);
                }
                let resp = user_api::sel_seller(order.clone().uid.unwrap().as_str()).await;
                let seller = resp.data;
                let order_vo = OrderVo {
                    seller,
                    info: order.clone(),
                    glist: Some(orderitem_vos),
                };
                order_vos.push(order_vo);
            }
            let msg = "获取成功";
            return HttpResponse::Ok().json(json!(Resp {
                symbol: 50,
                r#type: "success",
                code: 200,
                msg: msg,
                data: order_vos
            }));
        }
        Err(_) => {
            return HttpResponse::Ok().json(json!(Resp::bad("未知错误", -500, ())));
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct TmpData1<'a> {
    oid: &'a str,
}
